﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;
using System.Data;

namespace ST
{
    public partial class _Default : System.Web.UI.Page
    {
        public enum status
        {
            SearchResults,
            Playing
        }

        Video nextvideo = null;
        Feed<Video> related = null;
        static MyVideo[] vidsarr = null;
        static status currentStatus = status.SearchResults;
        static DataTable videos;


        protected void Page_Load(object sender, EventArgs e)
        {
            //Insure that the __doPostBack() JavaScript method is created...
            ClientScript.GetPostBackEventReference(this, string.Empty);
            if (!this.IsPostBack)
                Buttons.Style["display"] = "none";
            //if (this.IsPostBack)
            //{
            //    if (currentStatus == status.SearchResults)
            //    {
            //        //GridView1.Visible = true;
            //        //PanelPlayerButtons.Visible = false;
            //    }
            //    if (currentStatus == status.Playing)
            //    {
            //        GridView1.Visible = false;
            //        PanelPlayerButtons.Visible = true;
            //    }
            //    //ButtonGetRelated.Enabled = false;
            //    //string eventTarget = (this.Request["__EVENTTARGET"] == null) ?
            //    // string.Empty : this.Request["__EVENTTARGET"];
            //    //string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ?
            //    // string.Empty : this.Request["__EVENTARGUMENT"];

            //    //if (eventTarget == "callServersideMethod")
            //    //    GetRelatedVideos();
            //}
        }

        protected void OnPreRender(object sender, EventArgs e)
        {
            if (currentStatus == status.Playing)
            {
                DivTable.Style["Display"] = "none";
                Buttons.Style["Display"] = "inline";
                ytapiplayer.Style["Display"] = "inline";
            }
            if (currentStatus == status.SearchResults)
            {
                DivTable.Style["Display"] = "inline";
                Buttons.Style["Display"] = "none";
                ytapiplayer.Style["Display"] = "none";
            }
        }

        [System.Web.Services.WebMethod]
        public static MyVideo[] ButtonSearch_Click(string searchQuery)
        {
            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
            query.Query = searchQuery;
            query.ExtraParameters = "&format=5";
            query.OrderBy = "viewCount";
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;

            //Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/" + url);
            YouTubeRequest request = GetRequest();
            //request.Settings.Maximum = 20;
            //request.Settings.
            Feed<Video> videoFeed = request.Get<Video>(query);
            List<MyVideo> vids = new List<MyVideo>();
            int i = 0;
            foreach (Video v in videoFeed.Entries)
            {
                string[] tokens = v.Title.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                if (tokens.Length != 2)
                    continue;
                MyVideo mv = new MyVideo();
                mv.fullname = v.Title;
                mv.url = v.VideoId;
                mv.artist = tokens[0];
                mv.title = tokens[1];
                vids.Add(mv);
                i++;
                if (i > 20)
                    break;
            }
            vidsarr = vids.ToArray();
            currentStatus = status.SearchResults;
            return vidsarr;
        }

        [System.Web.Services.WebMethod]
        public static MyVideo[] GetRelatedVideos(string url)
        {
            //System.Diagnostics.Debugger.Break();
            //System.IO.StreamWriter sw = new System.IO.StreamWriter("test.txt");
            //sw.Write("related");
            //sw.Close();
            // ("Player's new state: " + newState);
            // Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/"+nextUrl.Attributes["href"]);
            Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/" + url);
            YouTubeRequest request = GetRequest();
            request.Settings.Maximum = 60;
            //request.Settings.AutoPaging = false;
            Video video = request.Retrieve<Video>(videoEntryUrl);
            Feed<Video> relatedVideos = request.GetRelatedVideos(video);
            //return relatedVideos[0];
            List<MyVideo> vids = new List<MyVideo>();
            int i = 0;
            foreach (Video v in relatedVideos.Entries)
            {
                i++;
                if (v.Media.Content != null && v.Media.Content.Attributes["format"] != null && v.Media.Content.Attributes["format"].Equals("5"))
                {
                    string[] tokens = v.Title.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                    if (tokens.Length != 2)
                        continue;
                    MyVideo mv = new MyVideo();
                    mv.fullname = v.Title;
                    mv.url = v.VideoId;
                    mv.artist = tokens[0];
                    mv.title = tokens[1];
                    vids.Add(mv);
                }
            }
            MyVideo[] vidsarr = vids.ToArray();
            currentStatus = status.Playing;
            return vidsarr;
            //related = relatedVideos;
            //Random rand = new Random();
            //int seed = rand.Next(relatedVideos.TotalResults);
            //int i = 0;
            //foreach (Video vid in relatedVideos.Entries)
            //{
            //    if (i == seed)
            //    {
            //        //nextVidTitle.InnerText = vid.Title;
            //        //if (nextUrl.Attributes["href"] != null)
            //        //    nextUrl.Attributes["href"] = vid.VideoId;
            //        //else
            //        //    nextUrl.Attributes.Add("href", vid.VideoId);
            //        //nextvideo = vid;
            //        return vid.Title;
            //        break;
            //    }
            //    i++;
            //}
            //return "failed";
            //nextVidTitle.InnerText = relatedVideos.Entries[0]
        }

        public static YouTubeRequest GetRequest()
        {
            YouTubeRequest request = HttpContext.Current.Session["YTRequest"] as YouTubeRequest;
            if (request == null)
            {
                YouTubeRequestSettings settings = new YouTubeRequestSettings("YouTubeAspSample",
                                                "ytapi-FrankMantek-TestaccountforGD-sjgv537n-0",
                                                "AI39si4v3E6oIYiI60ndCNDqnPP5lCqO28DSvvDPnQt-Mqia5uPz2e4E-gMSBVwHXwyn_LF1tWox4LyM-0YQd2o4i_3GcXxa2Q",
                                                HttpContext.Current.Session["token"] as string
                                                );
                settings.AutoPaging = true;
                request = new YouTubeRequest(settings);
                HttpContext.Current.Session["YTRequest"] = request;
            }
            return request;
        }

        protected void ButtonGetRelated_Click(object sender, EventArgs e)
        {
            //GetRelatedVideos();
        }

        protected void ButtonSearch_Click1(object sender, EventArgs e)
        {
            currentStatus = status.SearchResults;
            string searchQuery = TextBoxSearch.Text;
            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
            query.Query = searchQuery;
            query.ExtraParameters = "&max-results=20&format=5";
            query.OrderBy = "viewCount";
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;

            //Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/" + url);
            YouTubeRequest request = GetRequest();
            request.Settings.Maximum = 50;
            //request.Settings.
            Feed<Video> videoFeed = request.Get<Video>(query);
            videos = new DataTable();
            videos.Columns.Add("thumbnailUrl");
            videos.Columns.Add("title");
            videos.Columns.Add("videoId");
            foreach (Video v in videoFeed.Entries)
            {
                videos.Rows.Add(v.Thumbnails[0].Url, v.Title, v.VideoId);
                //MyVideo mv = new MyVideo();
                //mv.title = v.Title;
                //mv.url = v.VideoId;
                //mv.thumbnailUrl = v.Thumbnails[0].Url;
                //videos.Add(mv);
            }
            GridView1.DataSource = videos;
            GridView1.DataBind();
            GridView1.Visible = true;
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("ThisVideo"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = GridView1.Rows[index];
                string videoId = ((HiddenField)row.Cells[3].FindControl("hidden")).Value;
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "SCRIPT", "swfobject.embedSWF(" + videoId + ", \"ytapiplayer\", \"425\", \"356\", \"8\", null, null, params, atts);", true);
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //e.Row.Attributes.Add("onclick", "embed('" + ((HiddenField)e.Row.Cells[2].FindControl("hidden")).Value + "')");
                e.Row.Cells[1].Attributes.Add("onclick", "embed('" + ((HiddenField)e.Row.Cells[2].FindControl("hidden")).Value + "', '" + e.Row.Cells[1].Text + "')");
            }
        }

        protected void GridView1_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataSource = videos;
            GridView1.DataBind();
        }
    }
}
